package comgame.entities;

import com.almasb.fxgl.dsl.FXGL;
import com.almasb.fxgl.entity.*;
import javafx.util.Duration;
import comgame.components.AnimationComponent;
import comgame.components.AttributeComponent;
import comgame.components.HealthComponent;

import static com.almasb.fxgl.dsl.FXGL.tpf;

public class Enemy
{
    private Entity entity;
    private final AttributeComponent attribute;
    private final AnimationComponent animation;
    private final HealthComponent  health;
    public Enemy(Entity entity)
    {
        this.entity = entity;
        attribute = entity.getComponent(AttributeComponent.class);
        animation = entity.getComponent(AnimationComponent.class);
        health = entity.getComponent(HealthComponent.class);
    }
    public Entity getEntity()
    {
        return entity;
    }
    public void takeDamage(int amount) {
        health.takeDamage(amount);
        if (animation != null) {
            animation.playHurt();
        }
        if (health.getHealth() <= 0) {
            die();
        }
    }
    public void die() {
        if (animation != null ) {
            animation.playDie();

            // 禁用玩家控制
            entity.setProperty("canControl", false);

            // 移除实体（动画结束后）
            FXGL.runOnce(() -> {
                if (entity != null && entity.isActive()) {
                    entity.removeFromWorld();
                }
            }, Duration.seconds(1.5)); // 匹配死亡动画时长
        }
    }

    public boolean isCrit()
    {
        return Math.random() < attribute.getCritRate();
    }
    public void attack(Player target) {
        if (animation != null &&
                animation.getCurrentState() != AnimationComponent.AnimState.DEAD) {
            // 检查是否正在攻击中
            if (animation.getCurrentState() == AnimationComponent.AnimState.ATTACKING) {
                System.out.println("敌人正在攻击中，跳过此次攻击");
                return;
            }
            animation.playAttack(target.getEntity().getPosition());
            boolean isCrit = isCrit();
            FXGL.getGameTimer().runOnceAfter(() -> {
                double enemyAttack = this.getAttribute().getAttack(); // 敌人攻击力
                double playerDefense = target.getDefense(); // 玩家防御力（带装备加成）
                if(isCrit)
                {
                    target.takeDamage((int) ((Math.max(1, enemyAttack - playerDefense))*1.5));
                    System.out.println("对玩家暴击了T—T");
                }
                else
                {
                    target.takeDamage((int) Math.max(1, enemyAttack - playerDefense));
                }
            }, Duration.seconds(130*tpf()));
        }
    }

    public void setEntity(Entity entity) {
        this.entity = entity;
    }

    public AttributeComponent getAttribute() {
        return attribute;
    }

    public AnimationComponent getAnimation() {
        return animation;
    }

    public HealthComponent getHealth() {
        return health;
    }
}
